package net.hands.common.th;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

import javax.servlet.ServletException;

/**
 * 说明:异常工具 <br>
 * <p>
 * 这是一个开源的软件，请在LGPLv3下合法使用、修改或重新发布。
 * </p>
 * 
 * @author 陈侃(cknet@126.com, 13910090885)
 *         http://code.google.com/p/simpleframework/
 *         http://www.simpleframework.net
 */
public abstract class ThrowableUtils {
	/**
	 * 说明:获得原因
	 * 
	 * @param clazz
	 *            异常类
	 * @param throwable
	 *            异常对象
	 * @return Throwable
	 * @update 2012-9-25 上午10:57:21
	 */
	public static Throwable getCause(final Class<? extends Throwable> clazz,
			final Throwable throwable) {
		Throwable cause = throwable;
		while ((cause = cause.getCause()) != null && clazz.isAssignableFrom(cause.getClass())) {
			break;
		}
		return cause == null ? throwable : cause;
	}
  
	/**
	 * 说明:转换异常对象
	 * 
	 * @param th
	 *            异常对象
	 * @return Throwable
	 * @update 2012-9-20 上午10:17:45
	 */
	public static Throwable convertThrowable(Throwable th) {
		// 是服务异常
		if (th instanceof ServletException) {
			Throwable throwable = th;
			while (throwable != null && ServletException.class.isAssignableFrom(throwable.getClass())) {
				throwable = ((ServletException) throwable).getRootCause();
				if (throwable != null) {
					th = throwable;
				}
			}
		} else if (th instanceof UndeclaredThrowableException) {// 未声明异常
			final Throwable throwable = ((UndeclaredThrowableException) th).getUndeclaredThrowable();
			if (throwable != null) {
				th = throwable;
			}
		} else if (th instanceof InvocationTargetException) {// 是调用方法或构造方法所抛出异常
			th = ((InvocationTargetException) th).getTargetException();
		}
		return th;
	} 
}
